#define _CRT_SECURE_NO_WARNINGS 1

#include"seqlist.h"

void SLInit(SeqList* ps)
{
	assert(ps);

	ps->size = 0;
	ps->capacity = 4;
	STDataType* tmp = (STDataType*)malloc(sizeof(STDataType) * ps->capacity);
	if (tmp == NULL)
	{
		perror("SLInit:malloc");
		return;
	}
	ps->a = tmp;
}


void SLDestroy(SeqList* ps)
{
	assert(ps);

	if (ps->a != NULL)
	{
		free(ps->a);
		ps->a = NULL;
		ps->size = ps->capacity = 0;
	}
}


void Check_Capacity(SeqList* ps)
{
	assert(ps);

	if (ps->size == ps->capacity)
	{
		int newcapacity = 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("Check_Capacity:realloc");
			return;
		}
		ps->a = tmp;
		ps->capacity = newcapacity;
	}
}

void SLPushFront(SeqList* ps, STDataType x)
{
	assert(ps);

	Check_Capacity(ps);

	int end = ps->size;
	while (end > 0)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}


void SLPushBack(SeqList* ps, STDataType x)
{
	assert(ps);

	Check_Capacity(ps);

	ps->a[ps->size] = x;
	ps->size++;
}


void SLPrint(SeqList* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}


void SLPopFront(SeqList* ps)
{
	assert(ps);
	assert(ps->size > 0);

	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}


void SLPopBack(SeqList* ps)
{
	assert(ps);
	assert(ps->size > 0);

	ps->size--;
}


void SLInsert(SeqList* ps, int pos, STDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);

	Check_Capacity(ps);
	int end = ps->size;
	while (end > pos)
	{
		ps->a[end] = ps->a[end - 1];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}



void SLErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	assert(ps->size > 0);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}




